import { AnyArray, Caller, EventHandler } from './types';

export class EventManager {
    private eventMap: AnyArray<Caller> = {};
    static #instance: EventManager = null;
    private constructor() {}
    public static get instance(): EventManager {
        if (!EventManager.#instance) EventManager.#instance = new EventManager();
        return EventManager.#instance;
    }

    // 添加事件监听函数
    public addListener(eventName: string, callback: EventHandler, self: object) {
        let eventArray = this.eventMap[eventName];
        if (!eventArray) {
            this.eventMap[eventName] = [];
            eventArray = this.eventMap[eventName];
        }

        eventArray.push({
            callback: callback,
            self: self
        });
    }

    // 触发事件
    public emitEvent(eventName: string, data: any = {}): void {
        let eventArray = this.eventMap[eventName];
        if (!eventArray) {
            return;
        }
        for (let i = 0; i < eventArray.length; i++) {
            if (!eventArray[i]) continue;
            let caller = eventArray[i];
            caller.callback.call(caller.self, data, eventName);
        }
    }

    // 移除事件监听函数
    public removeListener(eventName: string, callback: EventHandler, self: object) {
        let eventArray = this.eventMap[eventName];
        if (!eventArray) {
            return;
        }
        for (let i = 0; i < eventArray.length; i++) {
            let caller = eventArray[i];
            if (caller.callback === callback && caller.self === self) {
                eventArray.splice(i, 1);
            }
        }
    }
}
